import {Button, Modal, Select, Popconfirm} from 'antd'
import React, {useState, useEffect} from 'react'
import {PlusOutlined} from '@ant-design/icons'
import type {ColumnsType} from 'antd/es/table'
import CustomTable from '@/components/Table'
import {getOutCarPage} from '@/service/storage/inAtorage'
import {carStatus} from '@/pages/carMessage/dict'
import styles from '../index.less'
import SearchForm from '@/components/SearchForm'
import {getCarTypeList} from '@/service/carMessage/list'
import {modelSeriesFun} from '@/utils/common'

interface DataType {
	outCarNo: string
	frameNo: string
	id?: string
	goodsType?: string
	vin?: string
	number?: string
	carFullName?: string
	goodsQuantity?: number
	carId?: string
}

const formItemLayout = {
	labelCol: {flex: '120px'},
	wrapperCol: {flex: '1'},
}

const materialTable = (props: any) => {
	const {companyId, cityId, data, setDataList} = props
	const [total, setTotal] = useState()
	const [modalTotal, setModalTotal] = useState()
	const [loading, setLoading] = useState(false)
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [modalParams, setModalParams] = useState({
		current: 1,
		size: 10,
	})
	const [vehicleList, setVehicleList] = useState<any[]>([])
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [carTypeList, setCarTypeList] = useState<any>([])
	const [tableData, setTableData] = useState(data)
	const [selectData, setSelectData] = useState(data)
	const [searchData, setSearchData] = useState({})

	// 获取品牌车系
	const onCarTypeListFun = () => {
		getCarTypeList().then((res: any) => {
			if (res?.success) {
				setCarTypeList(modelSeriesFun(res.data))
			}
		})
	}
	useEffect(() => {
		onCarTypeListFun()
	}, [])

	/** 获取车辆列表 */
	const getOutCarData = () => {
		setLoading(true)
		getOutCarPage({
			...modalParams,
			companyId,
			cityId,
			carStatus: 11,
			...searchData,
		})
			.then((res: any) => {
				setVehicleList(res.data.records)
				setModalTotal(res?.data?.total)
				setLoading(false)
			})
			.catch(() => {
				setVehicleList([])
				setLoading(false)
			})
	}
	useEffect(() => {
		if (companyId && cityId && isModalOpen) {
			getOutCarData()
		}
	}, [modalParams, companyId, cityId, isModalOpen])

	/** 选择的车辆列表分页 */
	useEffect(() => {
		const num = (params.current - 1) * params.size
		const datas = data.slice(num, params.current * params.size)
		if (datas?.length === 0 && params.current !== 1) {
			setParams({
				current: params.current - 1,
				size: params.size,
			})
		}
		setTableData(datas)
		setSelectData(data)
	}, [params, data])
	useEffect(() => {
		setTotal(data.length)
	}, [data])
	const columns: ColumnsType<DataType> = [
		{
			title: '车架号',
			dataIndex: 'frameNo',
			align: 'center',
			width: 140,
		},
		{
			title: '品牌/车系/车型',
			dataIndex: 'carModel',
			align: 'center',
			width: 160,
		},
		{
			title: '调出车牌号',
			dataIndex: 'outCarNo',
			align: 'center',
			width: 110,
		},
		{
			title: '调出车辆状态',
			dataIndex: 'outCarStatus',
			align: 'center',
			width: 140,
			render: (text) => (
				<Select
					value={Number(text)}
					disabled
					fieldNames={{value: 'key', label: 'label'}}
					options={carStatus}
				/>
			),
		},
		{
			title: '调出仓库',
			dataIndex: 'warehouseName',
			align: 'center',
			width: 140,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 80,
			render: (text: any, record) => (
				<Popconfirm
					title="确定要删除吗？"
					onConfirm={() => {
						const newData = selectData.filter(
							(item: any) => item.frameNo !== record.frameNo,
						)
						setDataList(newData)
						setSelectData(newData)
					}}
					okText="确定"
					cancelText="取消">
					<Button type="link" onClick={() => {}}>
						删除
					</Button>
				</Popconfirm>
			),
		},
	]
	const editCar = (record: any, type: string) => {
		if (type === 'add') {
			const newData = [...selectData]
			newData.push({
				frameNo: record?.vin,
				carModel: record?.carFullName,
				outCarNo: record?.number,
				outCarStatus: record?.carStatus,
				outWarehouse: record?.warehouseName,
				warehouseName: record?.warehouseName,
				carId: record?.carId,
			})
			setSelectData(newData)
		} else {
			setSelectData(
				selectData.filter((item: any) => item.frameNo !== record.vin),
			)
		}
	}

	const modalcolumns: ColumnsType<DataType> = [
		{
			title: '车架号',
			dataIndex: 'vin',
			align: 'center',
			width: 140,
		},
		{
			title: '车牌号',
			dataIndex: 'number',
			align: 'center',
			width: 110,
		},
		{
			title: '品牌/车系/车型',
			dataIndex: 'carFullName',
			align: 'center',
			width: 160,
		},
		{
			title: '车辆状态',
			dataIndex: 'carStatus',
			align: 'center',
			width: 150,
			render: (text) => (
				<Select
					value={Number(text)}
					disabled
					fieldNames={{value: 'key', label: 'label'}}
					options={carStatus}
				/>
			),
		},
		{
			title: '所属公司',
			dataIndex: 'companyName',
			align: 'center',
			width: 150,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 80,
			render: (text: any, record) => {
				const carData = selectData?.find(
					(item: any) => item?.frameNo === record?.vin,
				)
				return (
					<>
						{carData ? (
							<Button
								type="link"
								onClick={() => editCar(record, 'cancel')}>
								取消
							</Button>
						) : (
							<Button
								type="link"
								onClick={() => editCar(record, 'add')}>
								选择
							</Button>
						)}
					</>
				)
			},
		},
	]

	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '车架号',
					name: 'vin',
					key: 'vin',
				},
				{
					type: 'input',
					label: '车牌号',
					name: 'number',
					key: 'number',
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'select',
					key: 'fashionId',
					name: 'fashionId',
					label: '品牌/车系/车型',
					keys: 'id',
					title: 'fullName',
					items: carTypeList,
				},
				{},
			],
		},
	]
	const onFinish = (values: any) => {
		setSearchData(values)
		setModalParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		setSearchData({})
		setModalParams({
			current: 1,
			size: 10,
		})
	}

	const handleOk = () => {
		setDataList(selectData)
		setIsModalOpen(false)
		setSearchData({})
	}

	return (
		<div className={styles.vehicleTable}>
			<div className={styles.title}>
				调拨车辆
				<Button
					icon={<PlusOutlined />}
					type="primary"
					ghost
					size="small"
					style={{marginLeft: '24px'}}
					onClick={() => {
						setIsModalOpen(true)
					}}>
					选择车辆
				</Button>
				<span>已选择调拨车辆数量/辆：{data?.length}</span>
			</div>
			<CustomTable
				params={params}
				columns={columns}
				total={total}
				pagination
				callback={(pagination: any) => {
					setParams(pagination)
				}}
				loading={loading}
				dataSource={tableData}
			/>
			<Modal
				className={styles.vehicleMoadl}
				width={820}
				title="选择调拨车辆"
				destroyOnClose
				open={isModalOpen}
				onOk={handleOk}
				onCancel={() => {
					setSearchData({})
					setIsModalOpen(false)
				}}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
						btnStatus={false}
					/>
				</div>
				<CustomTable
					params={modalParams}
					columns={modalcolumns}
					total={modalTotal}
					pagination
					callback={(pagination: any) => {
						setModalParams(pagination)
					}}
					loading={loading}
					dataSource={vehicleList}
				/>
			</Modal>
		</div>
	)
}

export default materialTable
